/**
 * 流程设计器
 * @ver: 1.
 * @date: 2021-7-21
 * @author: cm.yu
 */
layui.config({
    base: 'js/module/',
}).extend({
    eleTree:'eleTree',
})
layui.use(['layer','form','element','util'],function(){
    var layer = layui.layer,
        form = layui.form,
        util = layui.util,
        element = layui.element;

    /* 全局tips */
    var openTips;
    $(document).on('mouseover mouseout','.layui-tips',function(event){
        if(event.type == "mouseover"){
            var tips = $(this).data('tips'),
                placement = $(this).data('placement'),
                _p;
            switch (placement) {
                case 'top':
                    _p = 1;
                    break; 
                case 'right':
                    _p = 2;
                    break;
                case 'bottom':
                    _p = 3;
                    break;
                 case 'left':
                    _p = 4;
                    break;
                default:
                    _p = 2;
                    break;
            };
            openTips = layer.tips(tips, $(this), {tips: [_p, '#2f4056'], time: 30000});        
        }else if(event.type == "mouseout"){
            layer.close(openTips);
        }
    });

    //全局tab 切换
    $(document).on('click','.tab-title li',function(){
        var _type = $(this).parent().data('type'),
            _index = $(this).index();
        $(this).addClass('current').siblings().removeClass('current');
        $('.tab-content[data-type='+_type+']').children('.tab-item').eq(_index).show().siblings().hide();
    });

    //容器
    var _el = $('#flow-main'),
        _elSet = $('#node-attr-form');

    var PARAMS = new Object(),//节点属性配置信息
        CONFIG = new Object();//流程属性配置信息

    //保存流程图
    $('.flow-save').click(function(){
        save();
    });
    function save() {
        var connects = [];//存储连线的数组
        var mainArr=[];//存储元素的数组
        $.each(jsPlumb.getAllConnections(), function (idx, connection) {
            console.log(connection)
            connects.push({
                ConnectionId: connection.id,
                start:$(connection.source).attr("data-index"),
                end:$(connection.target).attr("data-index"),
                originSign:$(connection.source).attr("data-sign"),
                destinationSign:$(connection.target).attr("data-sign"),
                sourcePoint:connection.endpoints[0].anchor.type?connection.endpoints[0].anchor.type:connection.endpoints[0].anchor.anchors[0].type,
                targetPoint:connection.endpoints[1].anchor.type?connection.endpoints[1].anchor.type:connection.endpoints[1].anchor.anchors[0].type,
                sourceId:connection.sourceId,
                targetId:connection.targetId,
                sourceUuid:connection.endpoints[0].anchor.id,
                targetUuid:connection.endpoints[1].anchor.id,
            });
        });
        $("#flow-main .flow-node").each(function(){
            mainArr.push({
                offset:$(this).position(),
                text:$(this).text(),
                index:$(this).attr("data-index"),
                sign:$(this).attr("data-sign"),
                icon:$(this).children('i').eq(0).attr('class'),
                id:$(this).attr('id'),
                type:$(this).attr("data-type")
            });
        });
        console.log(connects);
        console.log(mainArr);
        var config = form.val('flow-attribute-form');//流程属性配置
        sessionStorage.setItem("flowsheet",JSON.stringify({"connects":connects,"mainArr":mainArr,"params":PARAMS,"config":config}));
    }

    //清空流程图
    $('.flow-design-tools .del').click(function(){
        sessionStorage.removeItem('flowsheet');
        _el.html('');
        PARAMS = {};
        CONFIG = {};
        $('.flow-design-right .empty').show();
    });

    jsPlumb.ready(function() {
        var connectorPaintStyle = {//基本连接线样式
            lineWidth: 1.5,
            strokeStyle: "#9cd1f8",
            joinstyle: "round",
            outlineColor: "white",
            outlineWidth: 0
        };
        var connectorHoverStyle = {// 鼠标悬浮在连接线上的样式
            strokeWidth: 10,
            lineWidth: 1.5,
            strokeStyle: "#216477",
            outlineColor: "white",
            outlineWidth: 0,
        };
        var origin = {//起点
            endpoint: ["Dot", { radius: 5 }],  //端点的形状
            connectorStyle: connectorPaintStyle,//连接线的颜色，大小样式
            connectorHoverStyle: connectorHoverStyle,
            paintStyle: {
                strokeStyle: "#1E9FFF",
                fillStyle: "#fff",
                radius: 4,
                lineWidth: 1
            },        //端点的颜色样式
            hoverPaintStyle: {
                fillStyle: "#1E9FFF",
                radius:6
            },
            isSource: true,    //是否可以拖动（作为连线起点）
            connector: ["Flowchart", { stub: [40, 60], gap: 8, cornerRadius: 5, alwaysRespectStubs: false }],  //连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
            isTarget: false,    //是否可以放置（连线终点）
            maxConnections:-1,    // 设置连接点最多可以连接几条线,-1表示无限大
            connectorOverlays: [["Arrow", { width: 10, length: 10, location: 1 }]]
        };
        var destination = {//终点
            endpoint: ["Dot", { radius: 5 }],  //端点的形状
            connectorStyle: connectorPaintStyle,//连接线的颜色，大小样式
            connectorHoverStyle: connectorHoverStyle,
            paintStyle: {
                strokeStyle: "#1E9FFF",
                fillStyle: "#fff",
                radius: 4,
                lineWidth: 1            
            },
            isSource: false,    //是否可以拖动（作为连线起点）
            connector: ["Flowchart", { stub: [40, 60], gap: 8, cornerRadius: 5, alwaysRespectStubs: false }],  //连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
            isTarget: true,    //是否可以放置（连线终点）
            maxConnections:-1,    // 设置连接点最多可以连接几条线,-1表示无限大
            connectorOverlays: [["Arrow", { width: 10, length: 10, location: 1 }]]
        };
        $(".flow-design-tools").children('.item').draggable({
            helper: "clone",
            scope: "flow",
        });
        var elementSign=0;//标志元素唯一性
        $("#flow-main").droppable({
            scope: "flow",
            activate: function( event, ui ) {
                // console.log(event)
                // console.log(ui)
            },
            drop: function (event, ui) {//在目标(target)容器上释放鼠标 ,ui.draggable[0]为开始拖拽的元素
                elementSign++;
                var left = parseInt(ui.offset.left - $(this).offset().left);
                var top = parseInt(ui.offset.top - $(this).offset().top);
                var ele=$('<div class="flow-node active" data-sign="'+elementSign+'" data-index="'+$(ui.draggable[0]).attr("data-index")+'" data-type="'+$(ui.draggable[0]).attr("data-type")+'" >' + $(ui.helper).html() + '<span class="del layui-icon layui-icon-close-fill"></span></div>');//$(ui.helper).html()取第一个JQ元素的文本
                ele.css({"left":left,"top":top,position: "absolute",margin:0});
                $(this).append(ele);
                $(ele).siblings().removeClass('active');
                var _index = $(ui.helper).data('index');
                if(_index == 4 || _index == 6) {
                    jsPlumb.addEndpoint(ele, { anchors: "Top" }, destination);
                    jsPlumb.addEndpoint(ele, { anchors: "Left" }, destination);
                }else {
                    jsPlumb.addEndpoint(ele, { anchors: "Bottom" }, origin);//起点
                    jsPlumb.addEndpoint(ele, { anchors: "Right" }, origin);
                    jsPlumb.addEndpoint(ele, { anchors: "Top" }, destination);//终点
                    jsPlumb.addEndpoint(ele, { anchors: "Left" }, destination);
                }
                jsPlumb.draggable(ele,{containment: "parent"});//端点可以拖动设置,并且将端点限制在父级内
                // $(ele).draggable({ //设置拖动到main区域中的元素还可以拖拽
                //     containment: "parent", //限制拖动不超过父级边框
                //     grid: [10, 10]
                // });
                var id = $(ele).attr('id'),
                    type= $(ele).attr('data-type');
                jsonParams.add(id);
                addNodeAttr(type,id);
                if(!$(this).hasClass('_jsPlumb_connected')){
                    console.log(1)
                    $('#node-attr-form').prepend('<div class="jsplumb-connected-warm">节点尚未正确连接</div>');
                }
                $(ele).on('click',function(){
                    //console.log($(ele).attr('id'))
                    $(ele).addClass('active').siblings().removeClass('active');
                    addNodeAttr(type,id);

                    if(!$(this).hasClass('_jsPlumb_connected')){
                        $('#node-attr-form').prepend('<div class="jsplumb-connected-warm">节点尚未正确连接</div>');
                    }
                });
            }
        });

        //删除节点
        $("#flow-main").on("click", ".flow-node .del",function () {
            if (confirm("确定删除吗?")) {
                var id = $(this).parent().attr("id"),
                    index=$(this).parent().attr("data-index");
                jsPlumb.removeAllEndpoints(id);
                $(this).parent().remove();
                $(".flow-design-tools .item").each(function(){
                    if($(this).attr("data-index")==index){
                        $(this).removeClass("theGrey").draggable("enable"); // 激活其拖动功能
                    }
                });
                delete(PARAMS[id]);
            }
        });

        jsPlumb.bind("click", function (conn, originalEvent) {//点击线段删除
            if (confirm("确定删除吗?"))
            jsPlumb.detach(conn);
        });
        jsPlumb.bind("connection", function (connInfo, originalEvent) {//自己连自己管控     
            if (connInfo.connection.sourceId == connInfo.connection.targetId) {      
                alert("不能连接自己！");     
                setTimeout(function(){
                    jsPlumb.detach(connInfo.connection);      
                },100);
            }   
        });

        if(sessionStorage.getItem("flowsheet")){//判断是否有保存过
            var flowsheet=JSON.parse(sessionStorage.getItem("flowsheet"));
            var mainHTML=""
            for(var i=0;i<flowsheet.mainArr.length;i++){
                if(elementSign<flowsheet.mainArr[i].sign){//如果已经保存过,即将标记更新
                    elementSign=flowsheet.mainArr[i].sign;
                }
                mainHTML+='<div class="flow-node" data-sign="'+flowsheet.mainArr[i].sign+'" data-index="'+flowsheet.mainArr[i].index+'" id="'+flowsheet.mainArr[i].id+'" data-type="'+flowsheet.mainArr[i].type+'" style="left:'+flowsheet.mainArr[i].offset.left+'px;top:'+flowsheet.mainArr[i].offset.top+'px;position:absolute;margin:0" ><i class="'+flowsheet.mainArr[i].icon+'"></i><span class="name">' + flowsheet.mainArr[i].text + '</span><span class="del layui-icon layui-icon-close-fill"></span></div></div>';
            };
            $("#flow-main").append(mainHTML);
            $("#flow-main .flow-node").each(function(){
                var _index = $(this).data('index');
                if(_index == 4 || _index == 6) {
                    jsPlumb.addEndpoint(this, { anchors: "Top" }, destination);//终点
                    jsPlumb.addEndpoint(this, { anchors: "Left" }, destination);
                }else {
                    jsPlumb.addEndpoint(this, { anchors: "Bottom" }, origin);//起点
                    jsPlumb.addEndpoint(this, { anchors: "Right" }, origin);
                    jsPlumb.addEndpoint(this, { anchors: "Top" }, destination);//终点
                    jsPlumb.addEndpoint(this, { anchors: "Left" }, destination);
                }
                jsPlumb.draggable(this,{containment: "parent"});//端点可以拖动设置,并且将端点限制在父级内
                $(this).draggable({ //设置拖动到main区域中的元素还可以拖拽
                    containment: "parent", //限制拖动不超过父级边框
                });
                $(this).on('click',function(){
                    var id = $(this).attr('id'),
                        type = $(this).attr('data-type');
                    $(this).addClass('active').siblings().removeClass('active');
                    addNodeAttr(type,id);
                    if(!$(this).hasClass('_jsPlumb_connected')){
                        $('#node-attr-form').prepend('<div class="jsplumb-connected-warm">节点尚未正确连接</div>');
                    }
                })
            });
            //固定连线
            console.log(flowsheet)
            for(var i=0;i<flowsheet.connects.length;i++){
                console.log(flowsheet.connects[i])
                jsPlumb.addEndpoint(flowsheet.connects[i].sourceId, {
                  anchors: [flowsheet.connects[i].sourcePoint],
                  uuid: flowsheet.connects[i].sourceUuid
                },origin)
                jsPlumb.addEndpoint(flowsheet.connects[i].targetId, {
                  anchors: [flowsheet.connects[i].targetPoint],
                  uuid: flowsheet.connects[i].targetUuid
                },destination)
                connectEndpoint(flowsheet.connects[i].sourceUuid , flowsheet.connects[i].targetUuid);
            };
            //编码连接endPoint
            function connectEndpoint(from, to) {
                jsPlumb.connect({ uuids: [from, to] })
            };
            PARAMS = flowsheet.params;
            CONFIG = flowsheet.config;
            form.val('flow-attribute-form',{
                'remindWx':CONFIG.remindWx,
                'remindEmail':CONFIG.remindEmail,
                'withdraw':CONFIG.withdraw,
                'urge':CONFIG.urge,
                'open':CONFIG.open,
                'rule':CONFIG.rule
            });
        }
    });

    //节点属性设置
    function addNodeAttr(type,id) {
        console.log('type:',type,'ID:',id)
        element.tabChange('right-side-tab','1');
        $('.flow-design-right .empty').hide();
        _elSet.html(nodeAttr(id,type,PARAMS));
        form.render();
    };

    //节点属性设置
    var jsonParams = {
        add:function(id){
             PARAMS[id] = new Object();
        },
        set:function(data){
            // console.log(data)
            if(PARAMS[data.id][data.key]){
                PARAMS[data.id][data.key] = data.value;
            }else{
                PARAMS[data.id][data.key] = new Object();
                PARAMS[data.id][data.key] = data.value;
            }
        }
    }

    //编辑节点名称
    $(document).on('input propertychange','input[lay-set="nodename"]',function() {
        var id = _el.find('.active').attr('id');
        var val = $(this).val();
        _el.find('.active').find('.name').html(val);
        jsonParams.set({
            'id':id,
            'key':'name',
            'value':val
        })
    });

    /*******************************************     流程发起节点属性设置     **************************************************/
    //流程发起 - 节点操作 - 提交并打印
    form.on('switch(origin-print)',function(data){
        var id = _el.find('.active').attr('id');
        jsonParams.set({
            'id':id,
            'key':'print',
            'value':data.elem.checked
        })        
    });
    //流程发起 - 节点操作 - 暂存
    form.on('switch(origin-storage)',function(data){
        var id = _el.find('.active').attr('id');
        jsonParams.set({
            'id':id,
            'key':'storage',
            'value':data.elem.checked
        })
    });
    //流程发起 - 节点操作 - 结束流程
    form.on('switch(origin-end)',function(data){
        var id = _el.find('.active').attr('id');
        jsonParams.set({
            'id':id,
            'key':'end',
            'value':data.elem.checked
        })
    });
    //流程发起 - 节点操作 - 节点校验条件
    form.on('select(origin-check)',function(data){
        var _parent = $(data.elem).parents('.fdr-item');
        if(data.value == 1){
            if(_parent.next('.fdr-item-check').length > 0){
                _parent.next().show();
            }else{
                _parent.after('<div class="fdr-item fdr-item-check"><div style="flex:1"><a href="javascript:;" class="layui-btn layui-btn-primary layui-btn-fluid" lay-active="addCheck">添加校验条件</a></div></div>');
            }
        }else{
            _parent.next('.fdr-item-check').hide();
        }
    });
    util.event('lay-active', {
        //添加校验条件
        addCheck: function(othis){
            alert('添加校验条件');
        }
    });

    /*******************************************     流程节点属性设置     **************************************************/
    //启用抄送
    form.on('checkbox(node-enable-cc)',function(data){
        var _id = _el.find('.active').attr('id');
        $(data.elem).parent().next().toggle();
        if(data.elem.checked){
            jsonParams.set({
                'id':_id,
                'key':'ccChecked',
                'value':data.elem.checked
            })
        }else{
            delete(PARAMS[_id].ccChecked);
            delete(PARAMS[_id].ccMemberList);
        }
    });

    util.event('lay-active', {
        //点击设置负责任人
        addMember: function(othis){
            var _id = _el.find('.active').attr('id'),
                _thisId = $(othis).data('id'),
                _thisListLen = $(othis).find('ul').length;
            layer.open({
                type:1,
                area:['600px','600px'],
                title:'部门成员列表',
                btn:['确定','取消'],
                // content:$('#member-select'),
                content:memberList,
                success:function(layero,index){
                    if(_thisListLen > 0){
                        var _lis = $(othis).find('ul').html();
                        popupMemberRender(_lis);
                    }else{
                        popupMemberRender();
                    }
                },
                yes:function(index,layero){
                    if($(layero).find('.member-s-selected-list li').length > 0){
                        var _list = $(layero).find('.member-s-selected-list').html();
                        $(othis).html('<ul>'+_list+'</ul>');
                        var _departmentArr=[],_roleArr=[],_memberArr=[],_initiatorArr=[];
                        $(layero).find('.member-s-selected-list [data-type]').map(function(i,d){
                            var _type = $(d).data('type');
                            switch (_type) {
                                case 'department':
                                    _departmentArr.push($(d).data('id'));
                                    break;
                                case 'role':
                                    _roleArr.push($(d).data('id'));
                                    break;
                                case 'member':
                                    _memberArr.push($(d).data('id'));
                                    break;
                                case 'initiator':
                                    _initiatorArr.push($(d).data('id'));
                                    break;
                            }
                        })
                        jsonParams.set({
                            'id':_id,
                            'key':_thisId,
                            'value':{
                                html:_list,
                                department:_departmentArr,
                                role:_roleArr,
                                member:_memberArr,
                                initiator:_initiatorArr
                            }
                        })
                        console.log(PARAMS)
                    }else{
                        $(othis).html('<span class="empty-text"><i class="fa fa-user-plus"></i> 点击设置负责人</span>');
                        delete(PARAMS[_id][_thisId]);
                    }
                    layer.close(index);
                }
            })
        }
    });

});
